<?php

class Menu_model extends Model {

	var $currentLevel;

    function Menu_model()
    {
        parent::Model();

		$this->currentLevel = 0;
    }
	
	/**
	  * get_menu - Returns all of a single menu, including any child menus
	  *
	  * @author Daniel Wood
	  * @param $menu_id numeric id of the menu
	  * @return structured array, containing menu name, order on page, parent_id and all items
	  **/
    function get_menu($menu_id)
    {
		// The menu_id is essential, and must be numeric
		if($menu_id == "" || !isset($menu_id) || !is_numeric($menu_id)) {
			return false;
		}
		
		// Initialise return array
		$menu_array = array();

		$this->db->where('id', $menu_id);
        $query = $this->db->get('site_menu');
		if($query->num_rows()) {
			$row = $query->row();
			$menu_array['id-' . $this->currentLevel] = $row->id;
			$menu_array['title-' . $this->currentLevel] = $row->title;
			$menu_array['order-' . $this->currentLevel] = $row->order;
			$menu_array['parent_id-' . $this->currentLevel] = $row->parent_id;

			$this->db->where('menu_id', $menu_array['id-' . $this->currentLevel]);
			$this->db->order_by('order', 'asc');
			$query = $this->db->get('site_menuitems');
			
			$menu_array['items-' . $this->currentLevel] = array();
			foreach($query->result() as $row) {
				$itemHref = $row->href;

				if(is_numeric($itemHref)) {
					// Its a menu!
					$this->currentLevel++;
					$childMenu = $this->get_menu($itemHref);
					$menu_array['items'][] = $childMenu;
					$this->currentLevel--;
				} else {
					$item = array();
					$item['id-' + $this->currentLevel] = $row->id;
					$item['title-' + $this->currentLevel] = $row->title;
					$item['href-' + $this->currentLevel] = $itemHref;
					$menu_array['items'][] = $item;
				}
			}
		}
		
		return $menu_array;
    }

	/**
	  * get_menus - Returns menus using get_menu
	  *
	  * @author Daniel Wood
	  * @param parent_id optional parent menu id
	  * @return structured array, containing menus
	  **/
    function get_menus($parent_id = 0)
    {	
		$this->db->select('id');
		$this->db->where('parent_id', $parent_id);
		$this->db->order_by('order', 'asc');
        $query = $this->db->get('site_menu');

		$menus_array = array();
		foreach($query->result() as $row) {
			$menus_array[] = $this->get_menu($row->id);
		}
        
		return $menus_array;
    }

}

?>